﻿using System;
using System.Runtime.InteropServices;
using System.Configuration;
using Stasm.Properties;
using OpenCvSharp;
using System.IO;
using System.Reflection;

namespace Stasm
{
    public class StamsDLLImport
    {
        #region StamsDLLImport
        [DllImport(@"stasm_dll.dll", CallingConvention = CallingConvention.Cdecl)]
        protected static extern void AsmSearchDll(
            [Out] int[] pnlandmarks, // out: number of landmarks, 0 if can't get landmarks
            [Out] int[] landmarks, // out: the landmarks, caller must allocate
            [MarshalAs(UnmanagedType.LPStr)]string imagename, // in: used in internal error messages, if necessary
            IntPtr imagedata, // in: image data, 3 bytes per pixel if is_color
            int width, // in: the width of the image
            int height, // in: the height of the image
            int is_color, // in: 1 if RGB image, 0 if grayscale
            [MarshalAs(UnmanagedType.LPStr)]string conf_file0, // in: 1st config filename, NULL for default
            [MarshalAs(UnmanagedType.LPStr)]string conf_file1, // in: 2nd config filename, NULL for default, "" for none
            [MarshalAs(UnmanagedType.LPStr)]string sDataDir
        );
        #endregion

        public static StasmOutput AsmSearchDll(string imagePath, string sDataDir)
        {
            AppSettingsReader AppReader = new AppSettingsReader();

            StasmOutput retVal = null;
            int[] countLandmarks = new int[1];
            int[] containerLandmarks = new int[152];
            IplImage img = new IplImage(imagePath, LoadMode.GrayScale);
            string sConfigFile0 = Settings.Default["stasmConfigFile0"] as string;
            string sConfigFile1 = Settings.Default["stasmConfigFile1"] as string; ;
            if (!String.IsNullOrEmpty(sConfigFile0) && !String.IsNullOrEmpty(sConfigFile1))
            {
                string conf_file0 = String.Format("{0}{1}", sDataDir, sConfigFile0);
                string conf_file1 = String.Format("{0}{1}", sDataDir, sConfigFile1);
                AsmSearchDll(countLandmarks, containerLandmarks, imagePath, img.ImageData, img.Width, img.Height, 0, conf_file0, conf_file1, sDataDir);
                //Console.WriteLine(containerLandmarks[0]);
                //Console.WriteLine(containerLandmarks[1]);
                //Console.WriteLine(containerLandmarks[2]);
                retVal = new StasmOutput();
                retVal.ContainerLandmarks = containerLandmarks;
                retVal.CountLandmarks = countLandmarks;
            }
            return retVal;
        }
    }
}
